<template>
  <div class="w-full h-screen box-border relative overflow-hidden">
    <van-nav-bar safe-area-inset-top :border="false" >
      <template #right>
        <div class="lang-btn"  @click="showPicker = true">
          <span>{{ $t(lang) }}</span>
          <van-icon name="arrow" class="ml-[2px]" color="#000" />
        </div>
      </template>
    </van-nav-bar>
    <div class="h-full box-border px-4 pt-8 pb-2">
      <div class="flex flex-col gap-2">
        <div class="text-[25px]">{{ $t('welcomeToLogin') }}</div>
        <div class="text-[12px] text-black">
          <span>{{ $t('noAccountYet') }}</span>
          <span @click="router.push('/register')" class="text-red-600 cursor-pointer">
            {{ $t('toRegistry') }}
          </span>
        </div>
      </div>
      <van-config-provider :theme-vars="themeVars">
        <van-form @submit="login" class="!mx-2 !mt-12">
          <van-cell-group inset>
            <van-field 
              label=" "
              v-model="username"  
              name="username" 
              clearable
              label-width="0rem"
              :placeholder="$t('placeholder.enterAccount')" 
              :rules="phoneRules" 
            />
          </van-cell-group>
          <van-cell-group inset class="!mt-4">
            <PassWord 
              label=" "
              v-model="password"  
              name="password" 
              clearable
              label-width="0rem"
              :placeholder="$t('placeholder.enterPassWord')" 
              :rules="passwordRules" 
            />
          </van-cell-group>
          <div 
            class="flex justify-end items-center mt-4 mx-8 text-black text-[13px] cursor-pointer"
            @click="open(serverUrl)"
          >
            {{ $t('contactService') }}
          </div>
          <div class="mt-10 mx-4">
            <van-button 
              round 
              block 
              type="primary" 
              native-type="submit" 
              color="#000"
              :loading="loading"
            >
              <span class="text-white text-[16px]">
                {{ $t('login') }}
              </span>
            </van-button>
          </div>
          <div class="flex justify-center items-center mt-5 text-[13px] cursor-pointer">
            {{ $t('forgotPassword') }}
          </div>
        </van-form>
      </van-config-provider>
    </div>
    <van-number-keyboard safe-area-inset-bottom />
    <van-popup v-model:show="showPicker" round position="bottom">
      <van-picker
        :columns="columns.map(v => ({ text: t(v.text), value: v.value }))"
        @cancel="showPicker = false"
        @confirm="onConfirm"
      />
    </van-popup>
  </div>
</template>
<script setup lang="ts">
import PassWord from "@/components/Password/index.vue"

import { type FieldRule, closeToast } from "vant"

import { useI18n } from 'vue-i18n'

import { useRouter } from "vue-router"

import { useUserStore } from "@/store/user"

import { getI18nLanguage, SUPPORT_LOCALES_LIST, useLocales } from '@/i18n'

import  { loginItem } from "@/service/login"

import { open } from "@/utils/index"

const themeVars = { 
  cellBackground: "#F5F7F9",
  cellGroupInsetRadius: '300px',
  cellVerticalPadding: '12px'
}

const { t } =  useI18n({ useScope: 'global' })

const router = useRouter()

const user = useUserStore()

const lang = ref<string>(getI18nLanguage(user.lang))

const serverUrl = user.config ? user.config['customer.config.contactUrl'] : ''

const showPicker = ref<boolean>(false)

const columns = SUPPORT_LOCALES_LIST

const username = ref<string>('')
const password = ref<string>('')

const loading = ref<boolean>(false)

const onConfirm = ({ selectedValues }: { selectedValues: any[]}) => {
  useLocales(selectedValues[0])
  lang.value = getI18nLanguage(selectedValues[0])
  showPicker.value = false
}

const phoneRules: FieldRule[] = [{ 
  required: true, 
  message: t('rule.phoneNotEmpty'), 
  trigger: 'onBlur' 
}]

const passwordRules: FieldRule[] = [{ 
  required: true, 
  message: t('rule.passNotEmpty'), 
  trigger: 'onBlur' 
}]

const login = async () => {
  try {
    if (!(username.value && password.value)) return

    loading.value = true
    
    // showLoadingToast({
    //   message: '登录中...',
    //   duration: 0,
    //   forbidClick: true,
    //   overlay: true,
    // })

    const res = await loginItem({
      username: username.value,
      password: password.value,
    })

    loading.value = false

    if(!res.success) return 

    user.setToken(res.data)

    closeToast()

    // await user.loadUserInfo()
    await user.userInit()

    router.replace('/home')
  } catch(err){
    loading.value = false
    closeToast()
    throw err 
  }
}

</script>

<style lang="less" scoped>
:deep(.van-field__error-message) {
  position: absolute;
  top: 0;
  left: 38%;
}

.lang-btn {
  box-sizing: border-box;
  padding: 6px 10px 6px 14px;
  border: 1px solid #000;
  border-radius: 200px;
  font-size: 12px;
  font-weight: 500;
  background: rgba(255,255,255,0.45);
}
</style>
